package ThreadPool.lagou.concurrent.completableFuture.demo01;

import java.sql.Time;
import java.util.concurrent.*;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: CompletableFuture高阶使用
 * @date 2022/10/7 10:22
 */
public class CompletableFutureUserDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        extracted1();
    }

    private static void extracted() throws ExecutionException, InterruptedException {
        CompletableFuture<Object> objectCompletableFuture = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"come in...");
            int result = ThreadLocalRandom.current().nextInt(10);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return result;
        });
        System.out.println(Thread.currentThread().getName()+"线程先去忙其他的业务");
        System.out.println(objectCompletableFuture.get());
    }

    private static void extracted1()  {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(()->{
                System.out.println(Thread.currentThread().getName()+"come in...");
                int result = ThreadLocalRandom.current().nextInt(10);
                System.out.println("获取到的值为"+result);
                try {
                    TimeUnit.SECONDS.sleep(1);
                    if(result>5){
                        int num = 10/0;
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return result;
            },executorService).whenComplete((v,e)->{
                if(e==null){
                    System.out.println("------计算完成"+v);
                }
            }).exceptionally(e->{
                System.out.println("异常情况"+e.getCause()+"\t"+e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName()+"线程先去忙其他的业务");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            executorService.shutdown();
        }
        // 防止主线程立刻结束影响到我的异步线程计算结果
        // TimeUnit.SECONDS.sleep(3);

    }


}
